#pragma once

#include <iostream>
#include <string>
#include "InetAddr.hpp"
#include "Reactor.hpp"
class Reactor;

// 基类，将来以继承得方式分别实现Listener和IOService，以统一的方式看待listensocket和普通socket
class Connection
{
public:
    Connection()
    :_sockfd(-1)
    ,_events(0)
    {}
    ~Connection()
    {}
    // 一系列的获取方法
    int GetSockfd() { return _sockfd; }
    InetAddr GetPeer() { return _peer; }
    uint32_t GetEvents() { return _events; }
    Reactor* GetOwner() { return _owner; }
    std::string& GetInBuffer() { return _inbuffer; }
    std::string& GetOutBuffer() { return _outbuffer; }

    // 一系列的设置方法
    void SetSockfd(int sockfd) { _sockfd = sockfd; }
    void SetPeer(InetAddr& peer) { _peer = peer; }
    void SetEvents(uint32_t events) { _events = events; }
    void SetOwner(Reactor* reactor) { _owner = reactor; }

    void AppendInBuffer(const std::string& in)
    {
        _inbuffer += in;
    }

    void AppendOutBuffer(const std::string& out)
    {
        _outbuffer += out;
    }

    void EraseOutBuffer(int n)
    {
        _outbuffer.erase(0, n);
    }

    void Close() { close(_sockfd); }

    // Listener/IOService继承Connection后实现
    virtual void Recver() = 0;
    virtual void Sender() = 0;
    virtual void Excepter() = 0;
protected:
    int _sockfd;                // 该连接对应文件描述符
    InetAddr _peer;             // 客户端信息
    uint32_t _events;           // 关心的事件
    std::string _inbuffer;      // 输入缓冲区
    std::string _outbuffer;     // 输出缓冲区
    Reactor* _owner;            // 回指Reactor对象，方便后续连接管理

    // 时间戳进行保活测试
    // uint64_t _timestamp;
};